package com.tbit.uqbike.service.business.tag.strategy.add;

import cn.hutool.core.collection.CollectionUtil;
import com.tbit.uqbike.enums.TagOperationType;
import com.tbit.uqbike.object.business.UserInfo;
import com.tbit.uqbike.object.pojo.Machine;
import com.tbit.uqbike.object.pojo.tag.MachineTag;
import com.tbit.uqbike.object.pojo.vo.BatchOperationMsgVO;
import com.tbit.uqbike.webmanager.dto.TagBindDTO;
import com.tbit.uqbike.webmanager.resp.tag.TagResult;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 通过账户ID添加标签
 *
 *
 * @author <a href="mailto:chen.chaoxiong@tbit.com.cn">ChenChaoXiong</a>
 * @since 2024/7/12
 */
@Component
public class AddByAccountIdStrategy extends AbstractAddTagOperation{
    @Override
    protected BatchOperationMsgVO<TagResult> addTag(TagBindDTO tagBind) {
        Integer brandId = tagBind.getBrandId();
        Integer accountId = tagBind.getAccountId();
        UserInfo userInfo = tagBind.getUserInfo();

        if (CollectionUtil.isEmpty(tagBind.getTagIds())) {
            return BatchOperationMsgVO.empty();
        }
        Set<Long> tagIds = tagBind.getTagIds();
        List<Machine> machines = machineService.getByBrandIdAndAccountId(brandId, accountId);
        if (CollectionUtil.isEmpty(machines)) {
            return BatchOperationMsgVO.empty();
        }

        Set<Integer> machineIds = machines.stream()
                                          .map(Machine::getMachineId)
                                          .collect(Collectors.toSet());

        BatchOperationMsgVO<TagResult> results = new BatchOperationMsgVO<>();

        /**
         * ①移除不存在的标签ID后，校验集为空则中断流程并返回结果
         * ②移除不存在的设备ID后，校验集为空则中断流程并返回结果
         */
        if (!validateAndFilterTags(tagIds, brandId, accountId, results) || !validateAndFilterMachines(machineIds, brandId, accountId, results)) {
            return results;
        }
        List<MachineTag> addableMachineTags = caculateAddableMachineTags(machineIds, tagIds, brandId, accountId, userInfo,results);
        saveMachineTags(addableMachineTags,results);
        return results;
    }


    @Override
    public TagOperationType getOperationType() {
        return TagOperationType.ADD_BY_ACCOUNT_ID;
    }
}
